package com.simplegui.api;

import java.util.ArrayList;
import java.util.List;

public class FrameRateThread implements Runnable{
	
	private final DynamicFrame frame;
	private long sleepTime;
	private boolean running;
	
	private List<FrameRateListener> listeners;
	
	public FrameRateThread(DynamicFrame frame) {
		this.frame = frame;
		this.listeners = new ArrayList<>();
		setFrameRate(60);
		this.running = false;
	}
	
	public void setFrameRate(int frameRate) {
		this.sleepTime = 1000 / frameRate;
	}
	
	@Override
	public void run() {
		while (true){
			try {
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			frame.draw();
			callListeners();
		}
	}

	private void callListeners() {
		for (FrameRateListener listener : listeners) {
			listener.onDraw();
		}
	}
	
	public boolean isRunning() {
		return running;
	}
	
	public void addFrameHateListener(FrameRateListener listener){
		listeners.add(listener);
	}
	
	public void removeFrameHateListener(FrameRateListener listener){
		listeners.remove(listener);
	}

}
